<template>
  <div class="orderdetail-container">
    <div class="status">
      <div class="text">{{ orderTip }}</div>
      <img src="@/assets/images/car.png" alt width="80px" />
    </div>
    <div class="addressWrap">
      <div class="address">
        <div class="location flex-c-c">
          <van-icon name="logistics" />
        </div>

        <!-- Vue2必须保证有一级属性的存在，才可以访问其二级属性 -->
        <div class="info">
          <div>
            {{ address_info.name }} - {{ address_info.tel }} - {{ address_info.province }}- {{ address_info.city }}-
            {{ address_info.country }}-
            {{ address_info.addressDetail }}
          </div>
        </div>
        <van-divider />
      </div>
    </div>

    <van-card
      v-for="item in orderGoods"
      :key="item.id"
      :price="item.sell_price"
      :title="item.title"
      :thumb="item.thumb_path"
    >
    </van-card>

    <!-- 订单基本信息 -->
    <div class="orderInfo">
      <div class="item">
        <span>下单时间</span>
        <span>{{ unixToformatDate(orderInfo.add_time) }}</span>
      </div>
      <div class="item">
        <span>商品总价</span>
        <span>&yen; {{ orderInfo.total_price }}</span>
      </div>
      <div class="item">
        <span>商品数量</span>
        <span>{{ orderInfo.number }}</span>
      </div>
      <div class="item" v-if="orderInfo.status == 1">
        <span>实付款</span>
        <span>&yen; {{ orderInfo.actual_price }}</span>
      </div>
      <div class="item" v-if="orderInfo.status == 1">
        <span>付款时间</span>
        <span>{{ dateformat(orderInfo.success_time) }}</span>
      </div>
      <div class="item">
        <span>付款方式</span>
        <span>{{ orderInfo.pay_way }}</span>
      </div>
      <div class="item">
        <span>运费险</span>
        <span>&yen; 0.00</span>
      </div>
      <div class="item">
        <span>订单号</span>
        <div>
          <span>{{ orderInfo.order_id }} </span>
          <span class="copy" :data-clipboard-text="orderInfo.order_id">复制</span>
        </div>
      </div>
      <div class="item">
        <span>联系客服</span>
        <van-button size="mini" type="info" hairline plain @click="callPhone">联系客服</van-button>
      </div>
    </div>

    <!-- 订单操作按钮 -->
    <div class="btns">
      <template v-if="orderInfo.status === 0 && orderInfo.is_cancel === 0">
        <van-button @click="pay" type="danger" size="mini">立即付款</van-button>
        <van-button @click="cancelOrder" type="warning" size="mini">取消订单</van-button>
      </template>

      <van-button v-if="orderInfo.is_cancel === 1" type="warning" size="mini" disabled>订单已取消</van-button>
      <van-button size="mini" plain v-if="orderInfo.is_cancel == 1" type="warning" @click="delOrder">
        删除订单
      </van-button>
      <van-button v-if="orderInfo.is_out === 1" type="primary" size="mini" @click="showFlow">物流信息</van-button>

      <van-button v-if="orderInfo.is_out === 0 && orderInfo.status === 1" type="primary" size="mini"
        >提醒发货
      </van-button>
      <template v-if="orderInfo.is_finish === 1">
        <van-button type="info" size="mini">已完成</van-button>
        <van-button type="info" size="mini">去评价</van-button>
      </template>
    </div>

    <!-- 物流信息 -->
    <van-popup v-model="isShowFlow" position="bottom" :style="{ height: '50%' }">
      <!-- 目标收获地址 -->
      <div class="addressWrap">
        <div class="address">
          <div class="location flex-c-c">
            <van-icon name="location-o" />
          </div>

          <div class="info">
            <div>{{ address_info.name }} {{ address_info.tel }}</div>
            <div>
              {{ address_info.province }}{{ address_info.city }}{{ address_info.country
              }}{{ address_info.addressDetail }}
            </div>
          </div>
          <van-divider />
        </div>
      </div>
      <van-steps direction="vertical" :active="0">
        <van-step v-for="item in flow" :key="item.time">
          <h3>{{ item.location }}</h3>
          <p>{{ item.time }}</p>
        </van-step>
      </van-steps>
    </van-popup>

    <!-- 付款二维码 -->
    <van-dialog v-model="isShowQrcode" @confirm="payConfirm" title="扫码付款" confirmButtonColor="#f00">
      <img :src="img_url" />
    </van-dialog>
  </div>
</template>

<script>
import { reqWxPay, reqOrderInfo, reqQueryPayOrder, reqOrderFlow, reqCancelOrder, reqDelOrder } from '@/api/order'
import { reqCarGoods } from '@/api/user'
import { unixToformatDate, dateformat } from '@/utils/tool'
import QRCode from 'qrcode'
import ClipboardJS from 'clipboard'
export default {
  data() {
    return {
      order_id: this.$route.params.order_id,
      orderInfo: {},
      address_info: {},
      isShowQrcode: false,
      img_url: '',
      isPaying: false, // 用户是否在支付中
      orderGoods: [],
      isShowFlow: false,
      flow: [],
      checkStatusTimer: null,
    }
  },
  computed: {
    orderTip() {
      let { is_take, is_out, status, is_cancel, is_finish } = this.orderInfo
      if (status === 0 && is_cancel === 0) {
        return '等待付款'
      }

      if (status === 1 && is_out === 0) {
        return '等待发货'
      }

      if (is_out === 1 && is_take === 0) {
        return '你的包裹正在派送中'
      }

      if (is_finish === 1) {
        return '已完成'
      }

      if (is_cancel === 1) {
        return '已取消'
      }
      return ''
    },
  },
  watch: {
    isShowQrcode(newV) {
      if (!newV) {
        clearInterval(this.checkStatusTimer)
      }
    },
  },
  async mounted() {
    // 1. 获取订单数据
    await this.getOrderInfo()
    // 2. 获取订单关联的商品
    this.getCarGoods()

    // 初始化系统粘贴板
    this.initClipboard()

    // 检查订单状态
    this.checkOrderStatus()
  },

  methods: {
    unixToformatDate,
    dateformat,
    // 初始化系统粘贴板
    initClipboard() {
      const clipboard = new ClipboardJS('.copy')
      clipboard.on('success', () => {
        this.$toast('复制订单号成功')
      })
    },
    // 删除订单
    delOrder() {
      this.$dialog
        .confirm({
          message: '确认删除此订单吗',
          confirmButtonColor: '#ee0a24',
        })
        .then(async () => {
          let { code, message } = await reqDelOrder(this.orderInfo.order_id)
          this.$toast(message)
          if (code === 20000) {
            this.$router.back()
          }
        })
        .catch(() => {})
    },
    // 取消订单
    async cancelOrder() {
      let { code, message } = await reqCancelOrder(this.orderInfo.order_id)
      this.$toast(message)
      if (code === 20000) {
        // 1. 获取订单数据
        await this.getOrderInfo()
        // 2. 获取订单关联的商品
        this.getCarGoods()
      }
    },
    // 拨打电话
    callPhone() {
      this.$Dialog
        .confirm({
          message: '请拨打：13413132233',
          confirmButtonText: '拨打',
        })
        .then(() => {
          window.location.href = 'tel://' + 13411112222
        })
        .catch(() => {})
    },

    // 二维码确认按钮
    async payConfirm() {
      // 关闭订单检测且隐藏二维码弹窗
      clearInterval(this.timer)
      this.isShowQrcode = false
      // 用户可能提前关闭了二维码弹框，但已经提前支付了，所以要检测用户订单是否支付
      // 用户支付成功，但订单状态未改变，所以再去查询订单，及时更新订单为已支付
      let { code, message } = await reqQueryPayOrder(this.orderInfo.order_id)

      if (code === 20000) {
        // 支付成功
        this.$toast(message)
      }
      // 1. 获取订单数据
      await this.getOrderInfo()
      // 2. 获取订单关联的商品
      this.getCarGoods()
    },

    // 获取订单详情
    async getOrderInfo() {
      let orderInfo = await reqOrderInfo(this.order_id)
      this.orderInfo = orderInfo
      this.address_info = orderInfo.address_info
    },

    // 获取订单商品
    async getCarGoods() {
      let { message } = await reqCarGoods(this.orderInfo.goods_ids)
      this.orderGoods = message
    },

    // 用户点击付款
    async pay() {
      this.isPaying = true // 正在支付中
      console.log('orderInfo=>', this.orderInfo)

      // 1. 调用支付接口
      let orderData = {
        order_id: this.orderInfo.order_id,
        total_price: this.orderInfo.total_price,
      }
      let { status, data } = await reqWxPay(orderData)
      if (status === 200) {
        // 2. 弹框显示二维码-》用户扫码支付,将支付地址转换成二维码图片
        const img_url = await QRCode.toDataURL(data.code_url)
        this.isShowQrcode = true
        this.img_url = img_url
        // 3. 心跳检测，查询支付状态
        this.checkStatusTimer = setInterval(async () => {
          this.checkOrderStatus()
        }, 2000)
      }
    },

    // 查看物流
    async showFlow() {
      // 1. 获取物流接口
      let flow = await reqOrderFlow()
      this.flow = flow
      // 2. 显示弹窗
      this.isShowFlow = true
    },

    // 检查订单状态（ajax轮询检测订单状态(心跳检测：每间隔几秒获取订单状态（即轮询机制）)）
    async checkOrderStatus() {
      let { code } = await reqQueryPayOrder(this.orderInfo.order_id)
      if (code === 20000) {
        // 订单支付成功
        this.isShowQrcode = false
        clearInterval(this.checkStatusTimer)
        if (this.isPaying) {
          this.$toast.success({
            message: '付款成功',
            icon: 'wechat-pay',
          })
        }
        await this.getOrderInfo()
        this.getCarGoods()
      }
    },
  },

  beforeDestroy() {
    clearInterval(this.checkStatusTimer)
  },
}
</script>

<style lang="scss" scoped>
.orderdetail-container {
  height: 100vh;
  padding-bottom: 60px;
  background: #fff;

  .van-dialog {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .van-card {
    .van-card__thumb {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: space-around;
    height: 90px;
    font-size: 18px;
    color: #f5f5f5;
    background-color: #e35818;
  }

  .addressWrap {
    .address {
      display: flex;
      align-items: center;
      padding: 10px;
      margin: 6px 0;
      background-color: #fff;
      border-radius: 6px;

      .info {
        font-size: 14px;
      }

      .location {
        width: 30px;
        height: 30px;
        padding-left: 20px;
        margin-right: 20px;
        background: #f34a09;
        border-radius: 50%;
      }

      .van-icon {
        margin-right: 20px;
        font-size: 20px;
        color: #fff;
      }
    }
  }

  .orderInfo {
    padding: 2px 10px;

    .item {
      display: flex;
      justify-content: space-between;
      margin: 5px 0;
      font-size: 14px;
      color: #787373;
    }
  }

  .btns {
    position: fixed;
    right: 0;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    width: 100vw;
    height: 60px;
    padding: 0 10px;
    background-color: #fff;
    box-shadow: 0 0 10px #ccc;
  }
}
</style>
